/**
 * Created by Kpeng on 2017/7/3.
 * Depending on the jquery-1.12.4.min.js.
 * Depending on the common.js.
 * Depending on the style.min.css.
 * To cite this document, always state the source as shown above.
 * -------------------------------
 * Module:账号管理
 * -------------------------------
 */


$(function () {
  wzERP.Account.init();
});

wzERP.Account.init = function () {
  // wzERP.Account.addHandle();
  wzERP.Account.configHandle();
  //wzERP.Account.editHandle();
  //wzERP.Account.delHandle();
  wzERP.Account.isActive();
  wzERP.Account.turnPage();
  wzERP.Account.resetPassword();
  $('.ui.button.brown.configBtn2').on('click', function () {
    $('#manageRolePositionModal').modal({
      closable: false,
      transition: 'fade'
    }).modal('show')
  });
};

//添加帐号
$('.ui.button.blue.addAccountBtn').on('click', function () {
  $('#addOrUpdateAccountModal').modal({
    closable: false,
    transition: 'fade'
  }).modal('show')
  $("#addOrUpdateAccountModal").find("#transformation").text("添加账号")
  $("#addAccountForm").form("clear");
  $("#addAccountForm").find("[name='account']").removeAttr('readOnly');
  $("#addAccountForm").find(".passwordview").show();
  $('#addOrUpdateAccountModal .confirm').on('click', function () {
    var formdata = $("#addAccountForm").serializeArray();
    NetUtis.doPostFormSimple(Api.accountApi.addAcount.url, formdata,
        function (data) {
          if (data.success) {
            wzERP.Common.delayReload(wzERP.delayTime)
          }
        });
  });
})

//编辑帐号
function onEditAccountClick(id) {

  $('#addOrUpdateAccountModal').modal({
    closable: false,
    transition: 'fade'
  }).modal('show')
  $("#addOrUpdateAccountModal").find("#transformation").text("编辑账号")
  $("#addAccountForm").form("clear");
  $("#addAccountForm").find(".passwordview").hide();
  $("#addAccountForm").find("[name='account']").prop('readOnly', 'readOnly');
  $('#addOrUpdateAccountModal .confirm').on('click', function () {
    var formdata = $("#addAccountForm").serializeArray();
    NetUtis.doPostFormSimple(Api.accountApi.updateAccount.url, formdata,
        function (data) {
          if (data.success) {
            wzERP.Common.delayReload(wzERP.delayTime)
          }
        });
  });
  NetUtis.doGetSimple(Api.accountApi.queryAccountSimple.url, {id: id},
      function (data) {
        if (data.success) {
          var jData = data.data;
          var els = $("#addAccountForm").find("input");
          for (var i = 0; i < els.length; i++) {
            var dataName = $(els[i]).attr("name");
            console.info("账户编辑" + jData);
            if (dataName == undefined) {
              continue;
            }
            for (key in jData) {
              if (key == dataName) {
                $(els[i]).val(jData[key]);
              }
            }
          }

          var ops = $('#addAccountForm').find("option");
          for (var j = 0; j < ops.length; j++) {
            $(ops[j]).attr("selected", $(ops[j]).val() == jData.roleId)
            if ($(ops[j]).val() == jData.roleId) {
              $('#addAccountForm .roleList .default').text(
                  $(ops[j]).text()).removeClass("default");
            }
          }

        }
      }, true);
}

//删除帐号
function onDeleteAccountClick(id) {
  layer.alert('您确定要删除该数据?', {
        title: '提示信息',
        btn: ['取消', '确认'],
        btn1: function (index) {
          layer.close(index)
        },
        btn2: function () {
          NetUtis.doPostFormSimple(Api.accountApi.deleteAccount.url, {id: id},
              function (data) {
                if (data.success) {
                  wzERP.Common.delayReload(wzERP.delayTime)
                }
              });
        }
      }
  );

  /*layer.alert('您确定要删除该数据?', {
   title: '提示信息'
   },
   function () {
   NetUtis.doPostFormSimple(Api.accountApi.deleteAccount.url, {id: id}, function (data) {
   if (data.success) {
   wzERP.Common.delayReload(wzERP.delayTime)
   }
   });
   }
   );*/
}
//角色管理页面
$(".manageBtn").on("click", function () {
  $('#roleManageModal').removeClass('small').addClass('large');
  $('#roleManageModal').modal({
    closable: false,
    transition: 'fade'
  }).modal('show');
  wzERP.Common.loadHtml(
      wzERP.ViewDir + "/admin/role/account-manage.html?",
      '#roleManageModal .modalContent');
})

//岗位角色配页面
$(".configBtn").on("click", function () {
  $('#configManageModal').removeClass('small').addClass('large');
  $('#configManageModal').modal({
    closable: false,
    transition: 'fade',
    onApprove: function () {
      //
    }
  }).modal('show');
  wzERP.Common.loadHtml(
      wzERP.ViewDir + "/role/relation/account-config.html?",
      '#configManageModal .modalContent');
})

///////////////////////////////////////////////////////////////////////////////

//触发岗位角色配置
wzERP.Account.configHandle = function () {
  // var opt = {
  //     ele: '.configBtn',
  //     modalBox: '#modal',
  //     modalTitleStr: '岗位角色配置',
  //     onApprove: function () {
  //
  //     },
  //     snippets: $("#accountConfigHtml").val(),
  //     callback: function () {
  //         $('#modal').removeClass('small').addClass('large');
  //     }
  // };
  //wzERP.Common.handleData(opt);
};

//触发列表删除账号
wzERP.Account.delHandle = function () {
  var opt = {
    ele: '.delBtn',
    modalBox: '#modal',
    modalTitleStr: '',
    onApprove: function () {
      wzERP.Common.deleteData('#deleteAccoutUrl',
          $(this.modalBox).find('.setId'));
    },
    snippets: $("#accountDeleteHtml").val()
  };
  wzERP.Common.handleData(opt);
};

//触发列表重置密码
wzERP.Account.resetPassword = function () {
  var resetBtn = document.querySelectorAll('.resetBtn');
  $(document).on('click', '.resetBtn', function () {
    var param = {id: $(this).data('id')};

    layer.alert('您确定要重置密码吗？',
        {
          title: '提示信息',
          btn: ['取消', '确定'], //按钮
          btn1: function (index) {
            layer.close(index)
          },
          btn2: function () {
            var resetAccoutPwdUrl = $('#resetAccoutPwdUrl').val();
            $.post(resetAccoutPwdUrl, param, function (data) {
              switch (data.code) {
                case 0:
                  layer.msg(data.msg, {icon: 6, time: 1000});
                  break;
                case 9999: //超时
                  layer.msg(data.msg, {icon: 5});
                  wzERP.Common.TimeoutLogin();
                  break;
                default:
                  layer.msg(data.msg, {icon: 5, time: 1000});
              }
            });
          }
        })
  })
};

//触发列表激活状态
wzERP.Account.isActive = function () {
  var actives = $('#accountList').find('.toggle').find('input');
  actives.on('click', function () {
    var _this = $(this),
        opt = {
          ele: _this
        };
    wzERP.Common.slideCheck(opt);
  });
};

//岗位角色配置数据操作
wzERP.Account.configDataHandle = function () {
  var opt = {
    addBtn: '.addRoleBtn',
    template: '#temp',
    container: ".table-edit tbody",
    submitForm: "#submitForm",
    saveBtn: ".saveRoleBtn",
    editBtn: ".editRoleBtn",
    cancelBtn: ".cancelRoleBtn2",
    delBtn: ".delRoleBtn",
    saveFn: function () {
      wzERP.Common.saveHandle("#submitForm", "#addOrUpdateRoleRelationUrl",
          this.event, wzERP.Common.delayReload(wzERP.delayTime))
    },
    delFn: function () {
      wzERP.Common.deleteData('#deleteRoleRelationUrl', this.event);
    }
  };
  wzERP.Common.editTable(opt);
};

//删除岗位角色配置
wzERP.Account.delRoleRelateHandle = function () {
  var opt = {
    ele: '.delRoleRelateBtn',
    modalBox: '#modal',
    modalTitleStr: '',
    onApprove: function () {
      wzERP.Common.deleteData('#deleteAccoutUrl', $(this).find('.setId'));
    },
    snippets: $("#accountDeleteHtml").val()
  };
  wzERP.Common.handleData(opt);
};

//左侧列表联动右侧表单
wzERP.Account.roleListHandle = function () {
  var modal = $('#modal'),
      roleList = $('#roleList'),
      roleInfoForm = $('#roleInfoForm'),
      url = $("#queryRoleDetail").val(),
      checks = roleInfoForm.find('.table-wrap').find('input[type=checkbox]');

  //删除角色
  roleList.on('click', '.delRoleBtn', function () {
    var _this = $(this);
    layer.confirm('您确定要删除该角色？',
        {
          title: '提示信息',
          btn: ['取消', '确定'] //按钮
        },
        //取消事件
        function (index) {
          layer.close(index);
        },
        function () {
          var url = $('#deleteRole').val(),
              param = {id: _this.parent().attr('value')};
          $.post(url, param, function (data) {
                switch (data.code) {
                  case 0:
                    layer.msg(data.msg, {icon: 7, time: 1000});  //成功
                    wzERP.Common.delayReload(500);
                    break;
                  case 1:
                    layer.msg(data.msg, {icon: 5, time: 1000}); //失败
                    break;
                  default:
                    layer.msg(data.msg, {icon: 2, time: 1000});  //默认
                }
              },
              'json');
        });
    return false;
  });

  //创建角色
  modal.on('click', '.createRoleBtn', function () {
    checks.prop('checked', false);  //清空所有已选中
    $(this).find('.setId').removeAttr('data-id');
    modal.find('.createRoleText').text("创建角色");
    roleInfoForm.find('.role-base-info').show()
    .end().find('.table-wrap').css({maxHeight: "400px"})
    .end().find('.roleName').val('')
    .end().find('.desc').val('')
    .end().find('.ui.dropdown').dropdown('restore placeholder text');
  });
};

//分页跳转
wzERP.Account.turnPage = function () {
  var opt = {
    pageUrl: $("#accountPageUrl").val(),
    pageSearch: "#searchForm",
    pagesTotal: parseInt($('#pages').val()),
    pageCurr: parseInt($('#current').val()),
    pageSize: parseInt($('#pageSize').val()),
    currId: "#current"
  };
  wzERP.Account.pagingHandle(opt);
};

//分页操作
wzERP.Account.pagingHandle = function (_option) {
  /*Arg Guide
   @ option.pageCurr:当前页码
   @ option.pagesTotal:总页数
   @ option.pageSize:每页条数
   @ option.pageUrl: 目标页面
   @ option.currId: 传给后台的当前页数
   */

  var pageUrl = _option.pageUrl,
      pageCurr = _option.pageCurr,
      pageSize = _option.pageSize,
      pageSearch = _option.pageSearch,
      pagesTotal = _option.pagesTotal,
      currId = _option.currId;

  $(document).on('click', '.layui-laypage a', function () {
    if (!$('#configManageModal').hasClass('active')) {
      var getPageNum = parseInt($(this).data('page'));
      $(currId).val(getPageNum);
      $(pageSearch).action = pageUrl;
      $(pageSearch).submit();
    }
  });

  //直接跳至指定输入的页码
  $(document).on('click', '.layui-laypage-btn', function () {
    if (!$('#configManageModal').hasClass('active')) {
      var pageSkip = parseInt($('.layui-laypage-skip').val());
      if (pageSkip) {
        pageSkip = pageSkip > pagesTotal ? pagesTotal : pageSkip;  //超出总页数以末页输出
        $(currId).val(pageSkip);
        $(pageSearch).action = pageUrl;
        $(pageSearch).submit();
      }
    }
  });

  //select选择每页数目
  $(document).on('click', '.page-show-select .menu .item', function () {
    if (!$('#configManageModal').hasClass('active')) {
      var perPageNum = $(this).data('value');
      $('#pageSize').val(parseInt(perPageNum));
      $(currId).val(1);
      $(pageSearch).action = pageUrl;
      $(pageSearch).submit();
    }
  });

  layui.use(['laypage', 'layer'], function () {
    var laypage = layui.laypage;
    laypage({
      cont: 'turn-page',
      curr: parseInt(pageCurr),
      pages: pagesTotal,
      skin: '#457fe6',
      skip: true
    });
  });
};

//
function search() {
  $("#current").val(1);
  $("#searchForm").action = "/account/queryByPage";
  $("#searchForm").submit();
}

//表单验证器
wzERP.Account.verifier = function (_selector) {
  /*Arg Guide
   @_selector: 对象选择器
   */
  $(_selector).form({
    on: 'blur',
    // inline: true,
    transition: 'fade',
    fields: {
      //账号
      account: {
        identifier: 'account',
        rules: [{
          type: 'empty',
          prompt: '请输入账号'
        }]
      },
      //密码
      password: {
        identifier: 'password',
        rules: [{
          type: 'empty',
          prompt: '请输入密码'
        },
          {
            type: 'regExp[/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/]',
            prompt: '请输入8-20位数字及字母组合的密码'
          }]
      },
      //角色
      roleId: {
        identifier: 'roleId',
        rules: [{
          type: 'empty',
          prompt: '请选择角色'
        }]
      },
      //部门
      departId: {
        identifier: 'departId',
        rules: [{
          type: 'empty',
          prompt: '请选择部门'
        }]
      },
      //岗位
      positionId: {
        identifier: 'positionId',
        rules: [{
          type: 'empty',
          prompt: '请选择岗位'
        }]
      }
    }
  });
};

//分页跳转
wzERP.Account.turnPage1 = function () {
  var opt = {
    pageUrl: $("#accountConfigHtml").val(),
    pageSearch: "#searchForm",
    pagesTotal: parseInt($('#pages1').val()),
    pageCurr: parseInt($('#current1').val()),
    pageSize: parseInt($('#pageSize1').val()),
    currId: "#current1"
  };
  wzERP.Common.pagingHandle(opt);
};

//
